﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using ERP_RORZE_DLL.Product.DAO;
using ERP_RORZE_DLL.Product.database;
using ERP_RORZE_DLL.Product.Base;
using System.Data.OleDb;
using ERP_RORZE_PERMISSION.Base;
using ERP_RORZE_PRODUCT.Product.BusOder;
using ERP_RORZE_SYSTEM;
using System.Data.Common;
using System.Data.SqlClient;
using BaseDAO = ERP_RORZE_TOOL.DBAccess.BaseDAO;
using Utilities = ERP_RORZE_TOOL.Common.Utilities;

namespace ERP_RORZE_PRODUCT.Product.PartHandling
{
    public partial class ctrlBusInspDetail : DevExpress.XtraEditors.XtraUserControl
    {
        ClsPartHandlingDAO clsDAO = new ClsPartHandlingDAO();
        ClsDBusInspTable clsobj = new ClsDBusInspTable();
        DataTable dt;
        private LogUtils log;

        void Reload(object sender, EventArgs e)
        {
            dt = clsDAO.GetAllBusInspDetail();
            gridControl1.DataSource = dt;
            gridView1.BestFitColumns();
        }
        public ctrlBusInspDetail()
        {
            InitializeComponent();
            log = new LogUtils();
        }

        private void btnReload_Click(object sender, EventArgs e)
        {
            Reload(sender, e);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            clsobj.ID = int.Parse(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID").ToString());
            clsDAO.DeleteBusInspDetail(clsobj);

            //write Log
            log.Table = LogConstant.Table.Product.Bus_Insp;
            log.Task = LogConstant.Task.Delete;
            log.Description = "MONo: " + gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "MONo") + "; Date: " + gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "Date");
            log.WriteLog();

            Reload(sender, e);
        }

        private void btnInput_Click(object sender, EventArgs e)
        {
            frm_BusInspInput frmAdd = new frm_BusInspInput();
            frmAdd.Reload += new EventHandler(Reload);
            frmAdd.ShowDialog();
        }

        private void gridControl1_Load(object sender, EventArgs e)
        {
            Reload(sender, e);
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            Reload(sender, e);
        }

        private void btnAddNew_Click(object sender, EventArgs e)
        {
            btnInput_Click(sender, e);
        }

        private void btDelete_Click(object sender, EventArgs e)
        {
            btnDelete_Click(sender, e);
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            clsConstantsFuction.ExportToExcel(gridView1, 1, true);
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            //FileDialog fileDialog = new OpenFileDialog();
            //fileDialog.Filter = "Excel 2007-2013|*.xlsx|Excel 97-2003 (*.xls)|*.xls";
            //if (fileDialog.ShowDialog() == DialogResult.OK)
            //{
            //    OleDbConnection connection = new OleDbConnection();
            //    try
            //    {
            //        string path = fileDialog.FileName;
            //        INISettings iniSettings = new INISettings();
            //        string connectString = iniSettings.SQLConnectionString;
            //        // Connection String to Excel Workbook
            //        string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;Persist Security Info=False", path);

            //        connection.ConnectionString = excelConnectionString;
            //        OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
            //        connection.Open();
            //        // Create DbDataReader to Data Worksheet
            //        DbDataReader dr = command.ExecuteReader();

            //        // Bulk Copy to SQL Server 
            //        SqlBulkCopy bulkInsert = new SqlBulkCopy(connectString);
            //        bulkInsert.DestinationTableName = "[rrc_database].[dbo].[242_DBusInsp]";

            //        SqlBulkCopyColumnMapping toolId = new SqlBulkCopyColumnMapping("date", "date");
            //        bulkInsert.ColumnMappings.Add(toolId);

            //        SqlBulkCopyColumnMapping makerId = new SqlBulkCopyColumnMapping("MONo", "MONo");
            //        bulkInsert.ColumnMappings.Add(makerId);

            //        SqlBulkCopyColumnMapping PartID = new SqlBulkCopyColumnMapping("StaffID", "StaffID");
            //        bulkInsert.ColumnMappings.Add(PartID);

            //        SqlBulkCopyColumnMapping Qty = new SqlBulkCopyColumnMapping("BusQty", "BusQty");
            //        bulkInsert.ColumnMappings.Add(Qty);

            //        SqlBulkCopyColumnMapping Deadline = new SqlBulkCopyColumnMapping("Note", "Note");
            //        bulkInsert.ColumnMappings.Add(Deadline);

            //        SqlBulkCopyColumnMapping RawQty = new SqlBulkCopyColumnMapping("Finished", "Finished");
            //        bulkInsert.ColumnMappings.Add(RawQty);
            //        bulkInsert.WriteToServer(dr);

            //        connection.Close();
            //        Reload(sender, e);
            //    }
            //    catch (Exception ex)
            //    {
            //        MessageBox.Show(ex.Message);
            //        connection.Close();
            //    }
            //}

            ImportData();
        }

        private void ImportData()
        {
            INISettings mySetting = new INISettings();
            SqlConnection myConnection = new SqlConnection(mySetting.SQLConnectionString);

            int countOk = 0;
            int countDup = 0;
            int countErr = 0;

            List<Utilities.ListItem> listDup = new List<Utilities.ListItem>();
            List<Utilities.ListItem> listErr = new List<Utilities.ListItem>();
            FileDialog importFile = new OpenFileDialog();
            importFile.Filter = "Excel 2007-2013|*.xlsx|Excel 97-2003 (*.xls)|*.xls";
            if (importFile.ShowDialog() == DialogResult.OK)
            {
                OleDbConnection excelConnection = null;
                try
                {
                    Control parent = progressPanel1.Parent;
                    progressPanel1.Location =
                        new Point(parent.Bounds.X + parent.Bounds.Width / 2 - progressPanel1.Width / 2,
                                  parent.Bounds.Y + parent.Bounds.Height / 2 - progressPanel1.Height / 2);
                    progressPanel1.Visible = true;
                    string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                                                   importFile.FileName +
                                                   ";Extended Properties=Excel 12.0;Persist Security Info=False";
                    excelConnection = new OleDbConnection(excelConnectionString);
                    OleDbCommand cmd =
                        new OleDbCommand("Select [Date],[MONo],[StaffID],[BusQty] ,[Note] " +
                                         ",[Finished] from [Sheet1$]",
                                         excelConnection);
                    excelConnection.Open();
                    OleDbDataReader dReader;
                    dReader = cmd.ExecuteReader();
                    int i = 0;
                    int line = 1;
                    string lineDup = string.Empty;
                    string lineNo = string.Empty;

                    string Date = string.Empty;
                    string MONo = string.Empty;
                    string StaffID = string.Empty;

                    string BusQty = string.Empty;
                    string Note = string.Empty;
                    string Finished = string.Empty;


                    myConnection.Open();
                    while (dReader.Read())
                    {
                        bool exist = false;
                        line++;

                        //check null
                        try
                        {
                            //string dat = dReader["Date"].ToString();
                            //string qty = dReader["BusQty"].ToString();
                            if (dReader["Date"].ToString().Trim().Equals(string.Empty)
                                && dReader["MONo"].ToString().Trim().Equals(string.Empty)
                                && dReader["StaffID"].ToString().Trim().Equals(string.Empty)
                                && dReader["BusQty"].ToString().Trim().Equals(string.Empty)
                                && dReader["Note"].ToString().Trim().Equals(string.Empty)
                                && dReader["Finished"].ToString().Trim().Equals(string.Empty)
                                )
                            {
                                countErr++;
                                listErr.Add(new Utilities.ListItem(line.ToString(), dReader["Date"] + " | " + dReader["MONo"], "Null line"));
                                exist = true;
                            }
                        }
                        catch (Exception e)
                        {
                            countErr++;
                            listErr.Add(new Utilities.ListItem(line.ToString(), dReader["Date"] + " | " + dReader["MONo"], e.Message));
                            exist = true;
                        }

                        //check valid data
                        if (!exist)
                        {
                            try
                            {
                                Date = (dReader["Date"].ToString().Equals(string.Empty))
                                                ? "null"
                                                : "'" + DateTime.Parse(dReader["Date"].ToString()).ToShortDateString() + "'";
                                MONo = (dReader["MONo"].ToString().Equals(string.Empty))
                                                ? "null" : "'" + dReader["MONo"].ToString() + "'";
                                StaffID = (dReader["StaffID"].ToString().Equals(string.Empty))
                                                  ? "null" : "'" + dReader["StaffID"].ToString() + "'";

                                BusQty = (dReader["BusQty"].ToString().Equals(string.Empty))
                                             ? "null"
                                             : dReader["BusQty"].ToString();
                                Note = (dReader["Note"].ToString().Equals(string.Empty))
                                                ? "null"
                                                : "N'" + dReader["Note"].ToString() + "'";
                                Finished = (dReader["Finished"].ToString().Equals(string.Empty))
                                               ? "null"
                                               : "'" + dReader["Finished"].ToString() + "'";

                            }
                            catch (Exception ex)
                            {
                                exist = true;
                                listErr.Add(new Utilities.ListItem(line.ToString(),
                                                                   dReader["Date"] + " | " + dReader["MONo"],
                                                                   ex.Message));
                            }
                        }

                        if (!exist)
                        {
                            try
                            {
                                SqlCommand cmd_sql = myConnection.CreateCommand();
                                cmd_sql.CommandText = "SELECT * FROM [242_DBusInsp] WHERE [MONo]='" +
                                                      dReader["MONo"].ToString() + "' and [Date]='" +
                                                      dReader["Date"].ToString() + "'";
                                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                                if (dataReader.Read())
                                {

                                    exist = true;
                                    countDup++;
                                    listDup.Add(new Utilities.ListItem(line.ToString(), dReader["Date"] + " | " + dReader["MONo"], "Duplicate"));
                                }
                                dataReader.Close();
                                cmd_sql.Dispose();
                            }
                            catch (Exception e)
                            {
                                exist = true;
                                listErr.Add(new Utilities.ListItem(line.ToString(), dReader["Date"] + " | " + dReader["MONo"], e.Message));
                            }
                        }

                        //Insert to database
                        if (!exist)
                        {
                            try
                            {
                                string sql = "INSERT INTO [242_DBusInsp] ("
                                         + "[Date],[MONo],[StaffID],[BusQty]"
                                         + ",[Note] ,[Finished]  )"
                                         + " VALUES ( " + Date + ", " + MONo + ", " + StaffID + ","
                                         + BusQty + "," + Note + ", " + Finished + " )";
                                SqlCommand cmd_sql = new SqlCommand(sql, myConnection);

                                cmd_sql.ExecuteNonQuery();
                                cmd_sql.Dispose();
                                countOk++;

                                //write Log
                                log.Table = LogConstant.Table.Product.Bus_Insp;
                                log.Task = LogConstant.Task.Import;
                                log.Description = "MONo: " + MONo + "; Date: " + Date;
                                log.WriteLog();

                            }
                            catch (Exception ex)
                            {
                                listErr.Add(new Utilities.ListItem(line.ToString(), dReader["Date"] + " | " + dReader["MONo"], ex.Message));
                            }

                        }
                    }
                    myConnection.Close();
                    progressPanel1.Visible = false;
                    excelConnection.Close();
                    //MessageBox.Show(i + " records have been imported. \n" + countDup.ToString() + " record(s) duplicated (Lines: " + lineDup + ")\nLines have error OptionID: " + lineNo);
                    //LoadData();
                    Frm_ImportReport report = new Frm_ImportReport(countOk, listDup, listErr, "Bus Insp Detail");
                    report.StartPosition = FormStartPosition.CenterScreen;
                    report.Show();
                    report.Activate();
                }
                catch (Exception ex)
                {
                    if (excelConnection.State == ConnectionState.Open)
                    {
                        excelConnection.Close();
                    }
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    progressPanel1.Visible = false;
                    MessageBox.Show(ex.Message);
                }

            }
        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = sender as GridView;


            //Kiểm tra đây là dòng dữ liệu mới hay cũ, nếu là mới thì mình insert
            if (view.IsNewItemRow(e.RowHandle))
            {
                //e.RowHandle trả về giá trị int là thứ tự của dòng hiện tại

            }
            //Cũ thì update
            else
            {
                string BusQty = (view.GetRowCellValue(e.RowHandle, view.Columns["BusQty"]).ToString().Trim() == "") ? "null" : view.GetRowCellValue(e.RowHandle, view.Columns["BusQty"]).ToString();
                string id = (view.GetRowCellValue(e.RowHandle, view.Columns["ID"]).ToString().Trim() == "") ? "null" : view.GetRowCellValue(e.RowHandle, view.Columns["ID"]).ToString();

                string update = "update [242_DBusInsp] set [BusQty]=" + BusQty
                    + " where [ID] = " + id;
                if (BaseDAO.ExecuteNonQuery(update) > 0)
                {

                    //write Log
                    log.Table = LogConstant.Table.Product.Bus_Insp;
                    log.Task = LogConstant.Task.Update;
                    log.Description = "Change BusQty: " + BusQty + " where ID: " + id;
                    log.WriteLog();

                }

            }
        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Alt)
            {
                if (e.KeyCode == Keys.E)
                {
                    if (gridView1.OptionsBehavior.Editable)
                    {
                        gridView1.OptionsBehavior.Editable = false;
                    }
                    else
                    {
                        gridView1.OptionsBehavior.Editable = true;
                        gridView1.Columns["ID"].OptionsColumn.AllowEdit = false;
                        gridView1.Columns["Date"].OptionsColumn.AllowEdit = false;
                        gridView1.Columns["MONo"].OptionsColumn.AllowEdit = false;
                        gridView1.Columns["Finished"].OptionsColumn.AllowEdit = false;
                        gridView1.Columns["Note"].OptionsColumn.AllowEdit = false;
                        gridView1.Columns["StaffID"].OptionsColumn.AllowEdit = false;
                    }
                }
            }
        }


    }
}
